package com.multids.service.impl;

import com.multids.entity.DsOneDict;
import com.multids.entity.DsTwoDict;
import com.multids.mapper.db1.DsOneDictMapper;
import com.multids.mapper.db2.DsTwoDictMapper;
import com.multids.service.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Random;

@Service
public class DictServiceImpl implements DictService {

    @Resource
    DsOneDictMapper dsOneDictMapper;

    @Resource
    DsTwoDictMapper dsTwoDictMapper;

    @Override
    public void dicts() {
        DsOneDict one = dsOneDictMapper.selectById(1);
        System.out.println(one);
        DsTwoDict tow = dsTwoDictMapper.selectById(1);
        System.out.println(tow);

        DsOneDict byId = dsOneDictMapper.abc(1);
        System.out.println(byId);
        DsTwoDict twoById = dsTwoDictMapper.getTwoById(1);
        System.out.println(twoById);
    }

    /**
     * 不支持这种添加了事务注解（@Transactional）的方式，数据源始终会使用默认的，无法动态切换
     */
    @Transactional
    public void testTranst(){
        System.out.println("-----testTranst-----");
        DsOneDict dsOneDict = new DsOneDict();
        dsOneDict.setName("测试事务");
        int insert = dsOneDictMapper.insert(dsOneDict);
        System.out.println(insert);
        Random random = new Random();
        int r = random.nextInt(10);
        System.out.println("生成的随机数" + r);
        if(r % 2 == 0){
            System.out.println(10/0);
        }
        DsTwoDict dsTwoDict = new DsTwoDict();
        dsTwoDict.setName("未出异常测试事务" + r);
        dsTwoDictMapper.insert(dsTwoDict);
    }
}
